package com.chiu.widget;

import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.GradientDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;

/**
 * Created by zhouqing.qiu on 15-10-6.
 */
public class ShadowButton extends Button {
    private static final int ANIMATION_DURATION = 300;
    private int mDefBackground = 0XFFFFFFFF;
    private int mShadowBackground = 0XFFD3D3D3;
    private ObjectAnimator mColorAnim;
    private ArgbEvaluator mArgbEvaluator;
    private GradientDrawable mGradientDrawable;

    public ShadowButton(Context context) {
        super(context);
    }

    public ShadowButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShadowButton);
        mDefBackground = array.getColor(R.styleable.ShadowButton_defBackground, mDefBackground);
        mShadowBackground = array.getColor(R.styleable.ShadowButton_shadowBackground, mShadowBackground);

        mColorAnim = ObjectAnimator.ofFloat(this, "chiu", 0.0f, 1.0f).setDuration(ANIMATION_DURATION);
        mArgbEvaluator = new ArgbEvaluator();
        mGradientDrawable = (GradientDrawable) getBackground();
        mGradientDrawable.setColor(mDefBackground);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startShadowAnim();
                break;
            case MotionEvent.ACTION_UP:
                stopShadowAnim();
                break;
        }
        return super.onTouchEvent(event);
    }

    private void startShadowAnim() {
        mColorAnim.start();
        mColorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                int color = (int) mArgbEvaluator.evaluate(value, mDefBackground, mShadowBackground);
                mGradientDrawable.setColor(color);
            }
        });
    }

    private void stopShadowAnim() {
        mColorAnim.start();
        mColorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                int color = (int) mArgbEvaluator.evaluate(value, mShadowBackground, mDefBackground);
                mGradientDrawable.setColor(color);
            }
        });
    }
}
